<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/userStore'
import { useAuthStore } from '@/stores/authStore'
const router = useRouter()
const authStore = useAuthStore()
const userStore = useUserStore()

// 表单数据
const form = reactive({
  phone: '13800138899',
  code: ''
})

// 表单引用
const formRef = ref(null)
const submitting = ref(false)
const countdown = ref(0)

// 手机号验证规则
const isPhoneValid = computed(() => /^1[3-9]\d{9}$/.test(form.phone))

// 表单验证规则
/*const rules = reactive({
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码必须是6位数字', trigger: 'blur' }
  ]
})*/

// 发送验证码
const sendVerificationCode = async () => {
  try {
/*    // 验证手机号格式
    if (!isPhoneValid.value) {
      ElMessage.error('请输入正确的手机号')
      return
    }*/

    // 调用发送验证码接口
    await userStore.getSsmCode(form.phone)

    // 开始倒计时
    startCountdown()

      simulateSmsNotification()

    ElMessage.success('验证码已发送')
  } catch (error) {
    console.error('发送验证码失败:', error)
    ElMessage.error(error.message || '验证码发送失败')
  }
}

// 模拟短信通知（仅开发环境）
const simulateSmsNotification = () => {
  // 延迟几秒后显示验证码（模拟短信接收时间）
  setTimeout(() => {
    const code = userStore.ssmcode
    ElNotification({
      title: '短信验证码(开发环境)',
      message: `您收到的登录验证码是: ${code}`,
      type: 'info',
      duration: 0, // 不自动关闭
    })
  }, 2000)
}

// 60秒倒计时
const startCountdown = () => {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 处理登录
const handleLogin = async () => {
  submitting.value = true
  try {
    // 表单验证
    await formRef.value.validate()

    // 调用登录接口
    await authStore.smsLogin({
      mobile: form.phone,
      smsCode: form.code
    })

    // 登录成功处理
    ElMessage.success('登录成功')

    // 跳转到首页或其他页面
    router.push('/')
  } catch (error) {
    console.error('登录失败:', error)
    ElMessage.error(error.message || '登录失败，请检查验证码是否正确')
  } finally {
    submitting.value = false
  }
}

// 跳转到注册页面
const goToRegister = () => {
  router.push('/register')
}

// 显示其他登录方式
const showOtherLogin = () => {
  router.push('login')
}
</script>

<template>
  <div class="login-container">
    <div class="login-form">
      <h2 class="title">手机号登录</h2>

      <!-- 手机号输入 -->
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-position="top"
      >
        <el-form-item label="手机号" prop="phone">
          <el-input
              v-model="form.phone"
              placeholder="请输入手机号"
              clearable
              @keyup.enter="handleLogin"
          />
        </el-form-item>

        <!-- 验证码部分 -->
        <el-form-item label="验证码" prop="code">
          <div class="code-input">
            <el-input
                v-model="form.code"
                placeholder="请输入6位验证码"
                maxlength="6"
                @keyup.enter="handleLogin"
            />
            <el-button
                :disabled="!isPhoneValid || countdown > 0"
                @click="sendVerificationCode"
                class="send-btn"
            >
              {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>

        <!-- 登录按钮 -->
        <el-button
            type="primary"
            :loading="submitting"
            @click="handleLogin"
            class="login-btn"
        >
          登录
        </el-button>
      </el-form>

      <!-- 其他登录方式或注册链接 -->
      <div class="footer-links">
        <el-link type="primary" @click="goToRegister">注册账号</el-link>
        <el-divider direction="vertical" />
        <el-link type="primary" @click="showOtherLogin">账号密码登录</el-link>
      </div>
    </div>
  </div>
</template>



<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.login-form {
  width: 400px;
  padding: 40px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.title {
  text-align: center;
  margin-bottom: 30px;
  color: #303133;
}

.code-input {
  display: flex;
  gap: 10px;
}

.code-input :deep(.el-input) {
  flex: 1;
}

.send-btn {
  width: 120px;
}

.login-btn {
  width: 100%;
  margin-top: 20px;
}

.footer-links {
  margin-top: 20px;
  text-align: center;
  color: #909399;
}
</style>